package com.example.ffepeg.ffpeg;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
public class AudioDaYuvideo {
    public static void main(String[] args) throws Exception {
        String audio = "src/main/resources/file/filespaths/103ac92c-145b-41a8-8ef0-785604392044.wav";
        String video ="src/main/resources/file/filespaths/e684064d-c06f-48e4-bb3a-b9542f375097.mp4";
        String out = "src/main/resources/out/oup.mp4";
        merge(video,audio,out,27,6);
    }


    public static void merge(String videoFile, String audioFile, String outputFile, double audioDuration, double videoDuration) throws Exception {
        // 计算需要重复视频几次来匹配音频时长
        int repeatCount = (int) Math.ceil(audioDuration / videoDuration);

        // 构建文件列表内容
        StringBuilder fileListContent = new StringBuilder();
        for (int i = 0; i < repeatCount; i++) {
            fileListContent.append("file '").append(videoFile).append("'\n");
        }

        // 写入文件列表到磁盘
        String fileListPath = "filelist.txt"; // 假设在当前目录下创建
        Files.write(Paths.get(fileListPath), fileListContent.toString().getBytes());

        // 使用FFmpeg命令合并视频片段并匹配音频时长
        String[] ffmpegCommand = {
                "ffmpeg",
                "-f", "concat",
                "-safe", "0",
                "-i", fileListPath,
                "-i", audioFile,
                "-map", "0:v",
                "-map", "1:a",
                "-vsync", "vfr",
                "-t", String.valueOf(audioDuration),
                "-threads", "2",
                outputFile
        };

        // 执行FFmpeg命令，并加入异常处理以捕获执行过程中的错误
        try {
            Process process = new ProcessBuilder(ffmpegCommand).inheritIO().start();
            if (process.waitFor() != 0) {
                throw new Exception("FFmpeg command failed.");
            }
        } catch (Exception e) {
            System.err.println("Failed to execute FFmpeg: " + e.getMessage());
            throw e;
        }
    }





    public static void deleteFileContent(String path) {
        File filePath = new File(path);
        // 检查文件是否存在且是一个文件而不是目录
        if (filePath.exists() && filePath.isFile()) {
            boolean isDeleted = filePath.delete();
            if (isDeleted) {
                log.info("文件删除成功, {}",path);
            } else {
                log.info("文件删除失败, {}",path);
            }
        } else if (!filePath.exists()) {
            log.info("文件不存在");
        } else {
            log.info("无法删除，指定路径是一个文件夹而非文件");
        }
    }

    public static String createDirectoryAndCheckFile(String directoryPath, String createFileName) {
        // 生成唯一的文件名部分
        String uniquePart = UUID.randomUUID().toString().replaceAll("-", "") + System.currentTimeMillis();
        Path dirPath = Paths.get(directoryPath);
        Path pngFilePath = dirPath.resolve(uniquePart + createFileName);
        try {
            // 确保目录存在
            Files.createDirectories(dirPath);
            log.info("目录已创建或已经存在: " + dirPath);

            // 检查文件是否存在，若不存在则创建
            if (!Files.exists(pngFilePath)) {
                Files.createFile(pngFilePath);
                log.info("文件创建成功: " + pngFilePath);
            } else {
                log.info("文件已存在: " + pngFilePath);
            }
            // 返回带有正斜杠的相对路径字符串
            return pngFilePath.toString().replace(File.separator, "/");
        } catch (Exception e) {
            log.error("创建文件失败: " + pngFilePath, e);
            throw new RuntimeException("无法创建文件，请检查路径和文件名是否正确");
        }
    }


}
